package com.cmy.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //让浏览器定时刷新
        resp.setHeader("refresh","3");
        //在内存中创建图片
        BufferedImage img = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到画笔
        Graphics2D pen = (Graphics2D) img.getGraphics();
        //设置背景颜色
        pen.setColor(Color.WHITE);
        //填充
        pen.fillRect(0,0,80,20);//左上角坐标+长+宽
        //给图片写数据
        pen.setColor(Color.GREEN);
        pen.setFont(new Font(null, Font.BOLD,20));
        pen.drawString(makeRand(),0,20);
        //告诉浏览器,该请求用图片的方式打开
        resp.setContentType("image/jpg");
        resp.setHeader("expires", "-1");
        resp.setHeader("cache-control", "no-cache");
        resp.setHeader("pragma","no-cache");
        //把图片写给浏览器
        ImageIO.write(img,"jpg",resp.getOutputStream());


    }
    //生成随机数
    public String makeRand(){
        Random random = new Random();
        String num =  random.nextInt(999999)+"";
        StringBuffer sb = new StringBuffer();
        //保证六位
        for (int i = 0; i < 6-num.length(); i++) {
            int n = (int)Math.random() * 10;
            sb.append(n+"");
        }
        num = sb.toString()+num;
        return num;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

    